package com.bnlr.lrparking.appui.home;

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.event.CloseMainEvent;
import com.bnlr.lrparking.event.IntentEvent;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.VersionUtils;
import com.bnlr.lrparking.util.update.OkGoUpdateHttpUtil;
import com.bnlr.lrparking.view.NoSlideViewPager;
import com.google.gson.Gson;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author hp
 * @date 2017/8/14
 * App框架
 */
public class HomeActivity extends FragmentActivity {

    /**
     * 注解 Unbinder
     */
    private Unbinder unbinder;
    @BindView(R.id.viewPager)
    NoSlideViewPager viewPager;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    @BindView(R.id.btn_home)
    RelativeLayout rlHome;
    @BindView(R.id.img_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.btn_publish)
    RelativeLayout rlPublish;
    @BindView(R.id.img_publish)
    ImageView ivPublish;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.btn_me)
    RelativeLayout rlMe;
    @BindView(R.id.img_me)
    ImageView ivMe;
    @BindView(R.id.tv_me)
    TextView tvMe;
    String version = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        unbinder = ButterKnife.bind(this);
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        try {
            PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0);
            version = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            version = "1.0";
        }
        try {
            updateApp();
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        initView();
        Log.i("TAG", "homeactivity -- oncreat");
    }

    /**
     * 在线更新
     */
    private void updateApp() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<>();
        params.put("action", "GetUsingVersion");
        params.put("type", "1");
        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(Urls.COMMON)
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                .setTopPic(R.mipmap.update_head)
                .setThemeColor(0xff00CAA3)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
                // .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject object = new JSONObject(json);
                            // 判断请求结果是否正确
                            if (object.getInt("errorCode") == 0) {

                                JSONObject jsonObject = object.getJSONObject("data");
                                LogUtils.i("请求到版本信息", jsonObject.toString());
                                String isUpdate = "No";
                                if (VersionUtils.compareVersion(jsonObject.optString("VersioNnumber"), version) > 0) {
                                    isUpdate = "Yes";
                                }
                                LogUtils.i("是否需要更新 ----->>", isUpdate);
                                //（必须）是否更新Yes,No
                                updateAppBean.setUpdate(isUpdate)
                                        //（必须）新版本号
                                        .setNewVersion(jsonObject.optString("VersioNnumber"))
                                        //（必须）下载地址
                                        .setApkFileUrl(jsonObject.optString("LinkUrl"))
                                        //（必须）更新内容
                                        .setUpdateLog(jsonObject.optString("AppContent"))
                                        //大小，不设置不显示大小，可以不设置
                                        .setTargetSize(jsonObject.optString("Size"))
                                        //是否强制更新，可以不设置
                                        .setConstraint(jsonObject.optInt("IsForce") == 1 ? true : false);
                                LogUtils.i("updateAppBean ------->>", updateAppBean.toString());
                            } else {
                                LogUtils.i("请求新版本出错~~", object.getString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    /**
                     * 有新版本
                     *
                     * @param updateApp        新版本信息
                     * @param updateAppManager app更新管理器
                     */
                    @Override
                    public void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        // 强制更新，
                        if (updateApp.isConstraint()) {

                        } else {

                        }
                        try {
                            updateAppManager.showDialogFragment();
                        } catch (Exception e) {
                            LogUtils.e(e.getMessage());
                        }

                        //自定义对话框
                        //showDiyDialog(updateApp, updateAppManager);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {

                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {

                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                        //ToastUtils.showShort("没有新版本");
                        //Toast.makeText(JavaActivity.this, "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void initView() {
        Log.i("TAG", "homeactivity -- initView");
        EventBus.getDefault().register(this);
        mFragments.add(new StallDealFragment());
        mFragments.add(new PublishFragment());
        mFragments.add(new MeFragment());
        viewPager.setOffscreenPageLimit(mFragments.size() - 1);
        viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
        viewPager.setCurrentItem(0);
    }


    @OnClick({R.id.btn_home, R.id.btn_publish, R.id.btn_me})
    public void mainOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_home:
                startShakeByPropertyAnim(rlHome);
                viewPager.setCurrentItem(0);
                ivHome.setImageResource(R.mipmap.icon_home_sel);
                tvHome.setTextColor(getResources().getColor(R.color.main_color));
                ivPublish.setImageResource(R.mipmap.icon_release_nor);
                tvPublish.setTextColor(getResources().getColor(R.color.gray03_color));
                ivMe.setImageResource(R.mipmap.c);
                tvMe.setTextColor(getResources().getColor(R.color.gray03_color));
                break;
            case R.id.btn_publish:
                startShakeByPropertyAnim(rlPublish);
                viewPager.setCurrentItem(1);
                ivHome.setImageResource(R.mipmap.icon_home_nor);
                tvHome.setTextColor(getResources().getColor(R.color.gray03_color));
                ivPublish.setImageResource(R.mipmap.icon_release_sel);
                tvPublish.setTextColor(getResources().getColor(R.color.main_color));
                ivMe.setImageResource(R.mipmap.c);
                tvMe.setTextColor(getResources().getColor(R.color.gray03_color));
                break;
            case R.id.btn_me:
                startShakeByPropertyAnim(rlMe);
                viewPager.setCurrentItem(2);
                ivHome.setImageResource(R.mipmap.icon_home_nor);
                tvHome.setTextColor(getResources().getColor(R.color.gray03_color));
                ivPublish.setImageResource(R.mipmap.icon_release_nor);
                tvPublish.setTextColor(getResources().getColor(R.color.gray03_color));
                ivMe.setImageResource(R.mipmap.c1);
                tvMe.setTextColor(getResources().getColor(R.color.main_color));
                break;
            default:
                break;
        }
    }

    /**
     * 底部tab点击动画
     *
     * @param view
     */
    private void startShakeByPropertyAnim(View view) {
        if (view == null) {
            return;
        }
        //先变小后变大
        PropertyValuesHolder scaleXValuesHolder = PropertyValuesHolder.ofKeyframe(View.SCALE_X,
                Keyframe.ofFloat(0f, 1.0f),
                Keyframe.ofFloat(0.25f, 0.9f),
                Keyframe.ofFloat(0.5f, 1.2f),
                Keyframe.ofFloat(0.75f, 1.2f),
                Keyframe.ofFloat(1.0f, 1.0f)
        );
        PropertyValuesHolder scaleYValuesHolder = PropertyValuesHolder.ofKeyframe(View.SCALE_Y,
                Keyframe.ofFloat(0f, 1.0f),
                Keyframe.ofFloat(0.25f, 0.9f),
                Keyframe.ofFloat(0.5f, 1.2f),
                Keyframe.ofFloat(0.75f, 1.2f),
                Keyframe.ofFloat(1.0f, 1.0f)
        );

        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(view, scaleXValuesHolder, scaleYValuesHolder, scaleYValuesHolder);
        objectAnimator.setDuration(500);
        objectAnimator.start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinshMainEvent(CloseMainEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeViewPageEvent(IntentEvent event) {
        viewPager.setCurrentItem(1);
        ivHome.setImageResource(R.mipmap.icon_home_nor);
        tvHome.setTextColor(getResources().getColor(R.color.gray03_color));
        ivPublish.setImageResource(R.mipmap.icon_release_sel);
        tvPublish.setTextColor(getResources().getColor(R.color.main_color));
        ivMe.setImageResource(R.mipmap.c);
        tvMe.setTextColor(getResources().getColor(R.color.gray03_color));
    }

    public class MyViewPagerAdapter extends FragmentPagerAdapter {
        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    /**
     * 退出应用程序
     */
    private long exitTime = 0;

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.showShort("再按一次退出程序");
            exitTime = System.currentTimeMillis();
            return;
        } else {
            finish();
            System.exit(0);
        }
    }
}
